<?php

use swap\rdb_model;
use swap\value;

class user_model extends rdb_model {
	
	const email_min_length = 5;
	const email_max_length = 140;
	
	const password_min_length = 6;
	const password_max_length = 30;
	
	# rules
	public static function prop_rules($operation) {
		$rules = array(
			'reg' => self::email_rule($operation) + self::password_rule($operation),
			'login' => self::email_rule($operation) + self::password_rule($operation) + self::captcha_rule(),
		);
		return $rules[$operation];
	}
	protected static function email_rule($operation) {
		$rule = array(
			'email' => array(
				'change_to' => 'string',
				'cannot_be' => array('', 'E-mail地址不能为空'),
				'char_size' => array(self::email_min_length, self::email_max_length, '请填写一个有效的E-mail地址'),
				'value_type' => array(value::email_type, '请填写一个有效的E-mail地址'),
			),
		);
			
		if ($operation === 'reg') {
			$rule['email']['callback'] = function($email) {
				$user = user_model::get_one(array('email' => $email));
				if ($user !== null) {
					return '该E-mail地址已被注册了';
				}
			};
		}
		return $rule;
	}
	protected static function password_rule($operation) {
		$rule = array(
			'password' => array(
				'change_to' => 'string',
				'cannot_be' => array('', '密码不能为空'),
				'char_size' => array(self::password_min_length, self::password_max_length, '密码的长度为%d到%d个字符，区分大小写'),
			),
		);
		
		if ($operation === 'reg') {
			$rule['confirm'] = array(
				'same_as' => array('password', '两次密码不相同'),
			);
		}
		
		return $rule;
	}
	protected static function captcha_rule() {
		$rule = array(
			'validate' => array( // 前端过来的名称为validate
				'change_to' => 'string',
				'cannot_be' => array('', '请输入验证码'),
			),
		);
		return $rule;
	}
	
	public static function generate_password($password, $salt) {
		return sha1($password . $salt);
	}
	public function is_valid_password($password) {
		return $this->password === self::generate_password($password, $this->salt);
	}
	public function set_password($password) {
		$this->password = self::generate_password($password, $this->salt);
	}
	
}